//
//  MOForgotPasswordViewController.m
//  MobileOffice
//
//  Created by 晓 on 2019/6/8.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOForgotPasswordViewController.h"
#import "MOForgotPasswordViewCell.h"

@interface MOForgotPasswordViewController ()<UITableViewDelegate,UITableViewDataSource>

//返回登录按钮
@property (nonatomic, strong) UIButton *backLoginBtn;
//header
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) UITableView *tableView;
//数据数组
@property(nonatomic,strong)NSMutableArray *dataArray;
//footer
@property(nonatomic,strong)UIView *footerView;
//确认按钮
@property(nonatomic,strong)UIButton *sureSetButton;


@end

@implementation MOForgotPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatView];
    
    [self initData];
}

- (void)creatView{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backLoginBtn];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.tableHeaderView = self.headerView;
    
    self.tableView.tableFooterView = self.footerView;
}



-(void)initData
{
    self.dataArray = [NSMutableArray array];
    NSArray *nameArr = @[@"请输入用户名",@"请输入验证码",@"密码",@"再次输入新密码"];
    NSArray *paleArr = @[@"请输入用户名",@"请输入验证码",@"请输入6-20位新密码",@"请输入6-20位新密码"];
    for (int i = 0; i<4; i++) {
        MOForgotPasswordModel *model = [[MOForgotPasswordModel alloc]init];
        model.nameStr = nameArr[i];
        model.placeStr = paleArr[i];
        if (i==1) {
            model.type = @"1";
        }else{
            model.type = @"0";
        }
        if (i==2||i==3) {
            model.secureKeyword = @"1";
        }
//        model.showField = @"1";
//        model.fieldNameStr = @"验证码错误";
        [self.dataArray addObject:model];
    }
    [self.tableView reloadData];
}

#pragma mark -- 获取验证码
- (void)getTelCode
{
    MOForgotPasswordViewCell *cell0 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (cell0.textField.text.length==0) {
        //        [[ADShowMessage shareShowMessage] showTextOnly:@"请输入手机号" showInView:self.view];
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==0) {
                model.showField = @"1";
                model.fieldNameStr = @"手机号错误";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    for (int i = 0; i<self.dataArray.count; i++) {
        MOForgotPasswordModel *model = self.dataArray[i];
        if (i==0) {
            model.showField = @"0";
        }
    }
    [self.tableView reloadData];
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@",A_CAPTCHA_URL,@"MODIFYPWD",cell0.textField.text];
    
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"获取验证码:%@",responseObject);
        if ([responseObject integerValue]==0) {
            [[ADShowMessage shareShowMessage] showTextOnly:@"发送成功" showInView:self.view];
        }else if ([responseObject integerValue]==1){
            [[ADShowMessage shareShowMessage] showTextOnly:@"发送异常" showInView:self.view];
        }else if ([responseObject integerValue]==2){
            [[ADShowMessage shareShowMessage] showTextOnly:@"用户不存在" showInView:self.view];
        }else if ([responseObject integerValue]==3){
            [[ADShowMessage shareShowMessage] showTextOnly:@"用户为注册手机号码" showInView:self.view];
        }else{
            [[ADShowMessage shareShowMessage] showTextOnly:@"短信接口调用异常" showInView:self.view];
        }
    } failure:^(NSError *error) {
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -- 确认重置密码
-(void)clickSureResetButton
{
    MOForgotPasswordViewCell *cell0 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    MOForgotPasswordViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    MOForgotPasswordViewCell *cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    MOForgotPasswordViewCell *cell3 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    
    if (cell0.textField.text.length==0) {
//        [[ADShowMessage shareShowMessage] showTextOnly:@"请输入手机号" showInView:self.view];
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==0) {
                model.showField = @"1";
                model.fieldNameStr = @"手机号错误";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    if (cell1.textField.text.length==0) {
//        [[ADShowMessage shareShowMessage] showTextOnly:@"请输入验证码" showInView:self.view];
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==1) {
                model.showField = @"1";
                model.fieldNameStr = @"验证码错误";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    if (cell2.textField.text.length<6) {
//        [[ADShowMessage shareShowMessage] showTextOnly:@"请输入正确的密码" showInView:self.view];
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==2) {
                model.showField = @"1";
                model.fieldNameStr = @"密码格式错误";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    if (cell3.textField.text.length<6) {
//        [[ADShowMessage shareShowMessage] showTextOnly:@"请输入正确的确认的密码" showInView:self.view];
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==3) {
                model.showField = @"1";
                model.fieldNameStr = @"密码格式错误";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    
    if (![cell2.textField.text isEqualToString:cell3.textField.text]) {
//        [[ADShowMessage shareShowMessage] showTextOnly:@"两次输入密码不一致" showInView:self.view];
        for (int i = 0; i<self.dataArray.count; i++) {
            MOForgotPasswordModel *model = self.dataArray[i];
            if (i==3) {
                model.showField = @"1";
                model.fieldNameStr = @"两次输入密码不一致";
            }else{
                model.showField = @"0";
                model.fieldNameStr = @"";
            }
        }
        [self.tableView reloadData];
        return;
    }
    
    NSDictionary *parameters = @{
                                 @"userName":cell0.textField.text,
                                 @"password":[self sha1:[NSString stringWithFormat:@"%@%@",cell2.textField.text,cell0.textField.text]]
                                 };
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@",RESETPASSWORD_URL,cell1.textField.text];
    
    [[ADShowMessage shareShowMessage] showHUDAddedTo:self.view animated:YES];
    
    [PPNetworkHelper POST:postUrl parameters:parameters success:^(id responseObject) {
        NSLog(@"修改密码:%@",responseObject);
        
        [[ADShowMessage shareShowMessage] hideHUDForView:self.view animated:YES];
        
        if ([responseObject[@"code"] integerValue]==1) {//0：接口异常 1：接口正常
            
            [[ADShowMessage shareShowMessage] showTextOnly:@"密码重置成功" showInView:self.view];
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
            
        }else{
            [[ADShowMessage shareShowMessage] showTextOnly:responseObject[@"msg"] showInView:self.view];
            if ([responseObject[@"msg"] rangeOfString:@"验证码"].location!=NSNotFound) {
                for (int i = 0; i<self.dataArray.count; i++) {
                    MOForgotPasswordModel *model = self.dataArray[i];
                    if (i==1) {
                        model.showField = @"1";
                        model.fieldNameStr = @"验证码错误";
                    }else{
                        model.showField = @"0";
                        model.fieldNameStr = @"";
                    }
                }
                [self.tableView reloadData];
            }
        }
    } failure:^(NSError *error) {
        [[ADShowMessage shareShowMessage] hideHUDForView:self.view animated:YES];
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -//sha1加密方式
- (NSString *) sha1:(NSString *)input
{
    //这两句容易造成 、中文字符串转data时会造成数据丢失
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    //instead of
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MOForgotPasswordViewCell *setCell = [MOForgotPasswordViewCell cellWithTableView:tableView andIndexPath:indexPath];
    MOForgotPasswordModel *model = self.dataArray[indexPath.row];
    setCell.model = model;
    __weak typeof (self)weakSelf = self;
    setCell.clickCodeButtonBlock = ^{
        [weakSelf getTelCode];
    };
    setCell.endEditingBlock = ^(NSString * _Nonnull text) {
        model.valueStr = text;
    };
    
    return setCell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHConversions(12)*4+12+15+13;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0000001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        
    }
}

#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

#pragma mark -点击事件
- (void)clickBackLoginBtn{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 懒加载
- (UIButton *)backLoginBtn{
    if (!_backLoginBtn) {
        _backLoginBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 15)];
        [_backLoginBtn addTarget:self action:@selector(clickBackLoginBtn) forControlEvents:UIControlEventTouchUpInside];
        [_backLoginBtn setTitle:@"返回登录" forState:UIControlStateNormal];
        [_backLoginBtn setTitleColor:KTabbarBlueColor forState:UIControlStateNormal];
        _backLoginBtn.titleLabel.font = FONT_SIZE(15);
    }
    return _backLoginBtn;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-StatusBarAndNavigationBarHeight-TabbarSafeBottomMargin) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 111)];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 38, SCREEN_WIDTH - 70, 23)];
        titleLabel.text = @"请设置密码";
        if (@available(iOS 8.2, *)) {
            titleLabel.font = [UIFont systemFontOfSize:23 weight:UIFontWeightMedium];
        } else {
            titleLabel.font = [UIFont boldSystemFontOfSize:23];
        }
        titleLabel.textColor = KBlackColor_222222;
        
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, CGRectGetMaxY(titleLabel.frame) + 10, SCREEN_WIDTH - 70, 12)];
        textLabel.text = @"请重新设置您的密码";
        textLabel.font = FONT_SIZE(12);
        textLabel.textColor = KBlackColor_222222;
        
        [_headerView addSubview:titleLabel];
        [_headerView addSubview:textLabel];
    }
    return _headerView;
}

-(UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
        
        _sureSetButton = [[UIButton alloc]initWithFrame:CGRectMake(35, 10, SCREEN_WIDTH-70, 45)];
        [_sureSetButton setTitle:@"确认重置" forState:UIControlStateNormal];
        [_sureSetButton addTarget:self action:@selector(clickSureResetButton) forControlEvents:UIControlEventTouchUpInside];
//        [_sureSetButton setBackgroundColor:KBlueColor_B7DAFF];
        [_sureSetButton setBackgroundColor:KBlueColor_2C94FF];
        _sureSetButton.titleLabel.font = FONT_SIZE(15);
        _sureSetButton.layer.masksToBounds = YES;
        _sureSetButton.layer.cornerRadius = 3.0;
        [_footerView addSubview:_sureSetButton];
    }
    return _footerView;
}

@end
